package org.dromara.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.enums.WriteDirectionEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.dromara.basic.domain.vo.DeviceVo;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.excel.convert.ExcelBigNumberConvert;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class Utils {
    public static String toBase64(File file) {
        byte[] byt = null;
        try {
            byt = FileUtils.readFileToByteArray(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] encodedBytes = Base64.encodeBase64(byt);
        String str = new String(encodedBytes);
        return str;
    }
    public static List<DeviceVo> parseDeviceVoJson(String deviceVoJson){
        ObjectMapper objectMapper = new ObjectMapper();
        List<DeviceVo> deviceVos=new ArrayList<>();
        try {
            deviceVos = objectMapper.readValue(deviceVoJson, objectMapper.getTypeFactory().constructCollectionType(List.class, DeviceVo.class));
        } catch (IOException e) {
            throw new ServiceException("Json转换失败");

        }
        return deviceVos;
    }
    public static void myExportTemplate(List<Object> data, String templatePath, OutputStream os) {
        ClassPathResource templateResource = new ClassPathResource(templatePath);
        ExcelWriter excelWriter = EasyExcel.write(os)
            .withTemplate(templateResource.getStream())
            .autoCloseStream(false)
            // 大数值自动转换 防止失真
            .registerConverter(new ExcelBigNumberConvert())
            .build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        if (CollUtil.isEmpty(data)) {
            throw new IllegalArgumentException("数据为空");
        }

        // 单表多数据导出 模板格式为 {.属性}
        FillConfig fillConfig = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).forceNewRow(Boolean.TRUE).build();
        for(int i=0;i<data.size();i++){
            excelWriter.fill(data.get(i), fillConfig,writeSheet);
        }
//        for (Object d : data) {
//
//        }
        excelWriter.finish();
    }
}
